package com.base.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;

public class RecordtoTreeJson {

    //递归获取树型结构数据
    public static List<Map<String, Object>> recursion(String id, List<Map<String, Object>> listData) throws Exception {
        List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
        Iterator it = listData.iterator();
        while (it.hasNext()) {
            Map<String, Object> map = (Map<String, Object>) it.next();
            if ("".equals(map.get("parentId")) || map.get("parentId").equals(id)) {
                treeList.add(map);
                //使用Iterator，以便在迭代时把listData中已经添加到treeList的数据删除，迭代次数
                it.remove();
            }
        }
        for (Map<String, Object> map : treeList) {
            map.put("children", recursion((String) map.get("id"), listData));
        }
        return treeList;
    }

    //Object转Map
    public static Map<String, Object> getObjectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            if (value == null) {
                value = "";
            }
            map.put(fieldName, value);
        }
        return map;
    }

}
